import datetime
import os
from loguru import logger

# base on: https://www.cnblogs.com/hoyun/p/14004349.html
from pythonarchetype.overall.ProjectPath import project_path


def ensure_directory(log_path):
    if not os.path.isdir(log_path):
        os.makedirs(log_path)


class LoguruAdapter(object):
    __instance = None
    has_configured = False

    # 文件名称，按天创建
    DATE = datetime.datetime.now().strftime('%Y-%m-%d')

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(LoguruAdapter, cls).__new__(cls, *args, **kwargs)

        return cls.__instance

    def config(self, cfg):
        if self.has_configured:
            return

        self.has_configured = True

        log_path = project_path.root_path + cfg.log.path
        ensure_directory(log_path)

        filename = cfg.log.filename % (cfg.application, self.DATE)

        logger.add(f'{log_path}/{filename}',  # 指定文件
                   format=cfg.log.format,
                   encoding=cfg.log.encoding,
                   retention=cfg.log.retention,  # 设置历史保留时长
                   backtrace=cfg.log.backtrace,  # 回溯
                   diagnose=cfg.log.diagnose,  # 诊断
                   enqueue=cfg.log.diagnose,  # 异步写入
                   serialize=cfg.log.serialize
                   # rotation="5kb",  # 切割，设置文件大小，rotation="12:00"，rotation="1 week"
                   # filter="my_module"  # 过滤模块
                   # compression="zip"   # 文件压缩
                   )
        logger.info(f'log path: {log_path}/{filename}')

        return logger
